﻿namespace EyeOpen.IO
{
    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Text;

    internal class CompressionService
    {
        internal string Compress(string toCompress)
        {
            var buffer = Encoding.UTF8.GetBytes(toCompress);
            byte[] compressed;
            using (var ms = new MemoryStream())
            {
                using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
                {
                    zip.Write(buffer, 0, buffer.Length);
                }

                ms.Position = 0;

                compressed = new byte[ms.Length];
                ms.Read(compressed, 0, compressed.Length);
            }

            var gzBuffer = new byte[compressed.Length + 4];
            Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);

            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);

            return Convert.ToBase64String(gzBuffer);
        }

        internal string Decompress(string toDecompress)
        {
            var gzBuffer = Convert.FromBase64String(toDecompress);
            var msgLength = BitConverter.ToInt32(gzBuffer, 0);
            var buffer = new byte[msgLength];
            using (var ms = new MemoryStream())
            {
                ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

                ms.Position = 0;
                using (var zip = new GZipStream(ms, CompressionMode.Decompress))
                {
                    zip.Read(buffer, 0, buffer.Length);
                }
            }

            return Encoding.UTF8.GetString(buffer);
        }
    }
}
